package com.wpml.netty.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Description
 * @Date 2021-07-16
 * @Author wangpei
 **/
public class ClientMain {

    public static void main(String[] args) throws IOException {
        SocketChannel client = SocketChannel.open();
        client.configureBlocking(false);
        client.connect(new InetSocketAddress("127.0.0.1", 9090));

        while (client.finishConnect()) {
            System.out.println("等待非阻塞连接建立...." + client.socket().getPort() + " " +client.getLocalAddress());

            InputStream in = System.in;
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line = reader.readLine();

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            if (line != null) {
                buffer.put(line.getBytes(StandardCharsets.UTF_8));
                buffer.flip();
                client.write(buffer);
            }
            buffer.clear();
            System.out.println("=================");


            while (true) {
                int read = client.read(buffer);
                System.out.println("read  " + read);
                if (read > 0) {
                    buffer.flip();
                    byte[] bytes = new byte[buffer.limit()];
                    while (buffer.hasRemaining()) {
                        buffer.get(bytes,0, read);
                        System.out.println(new String(bytes, 0, bytes.length));
                    }
                    buffer.clear();
                } else {
                    break;
                }
            }


//            client.close();

        }




    }
}
